package cn.edu.scnu.Admin.service;

import cn.edu.scnu.Admin.mapper.AdminMapper;
import cn.edu.scnu.pojo.MatchActivity;
import cn.edu.scnu.pojo.Organizer;
import cn.edu.scnu.utils.PrefixKey;
import cn.edu.scnu.vo.OrganizerVO;
import cn.edu.scnu.vo.PersonalUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisCluster;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

@Service
public class AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private JedisCluster jedis;


    public List<MatchActivity> getAllmatches() {
        return adminMapper.getAllmatches();
    }

    public List<OrganizerVO> getAllOrganizer() {
        return adminMapper.getAllOrganizer();
    }

    public List<PersonalUserVO> getAllPersonalUser() {
        return adminMapper.getAllPersonalUser();
    }

    public void modifyState(String matchId) {
        if (matchId.charAt(0)=='"')
            matchId=matchId.replace("\"","");
        String matchKey = PrefixKey.MATCH_QUERY_PREFIX + matchId;
        //修改前删除缓存
        Long remainTime = jedis.ttl(matchKey);
        jedis.del(matchKey);
        //加锁
        String lock = PrefixKey.MATCH_UPDATE_PREFIX + matchId + ".lock";
        jedis.setex(lock, Integer.parseInt(remainTime + ""), "");
        adminMapper.modifyState(matchId);
        //释放锁
        jedis.del(lock);
    }

    public void delUser(String userId) {
        if (userId.charAt(0)=='"')
            userId=userId.replace("\"","");
        adminMapper.delUser(userId);
    }

    public void modifyUserInfo(PersonalUserVO personalUser) {
        adminMapper.modifyUserInfo(personalUser);
    }

    public void modifyOrgInfo(OrganizerVO orgUser) {
        adminMapper.modifyOrgInfo(orgUser);
    }

    public void modifyMatchInfo(MatchActivity match) {
        match.setUpdateTime(new Timestamp(new Date().getTime()));
        adminMapper.modifyMatchInfo(match);
    }
}
